import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
from backend.app import db
def get_lottery_model():
    from backend.models.lottery_result import LotteryResult
    return LotteryResult
import time
import logging

class LotteryService:
    """双色球数据服务"""
    
    def __init__(self):
        self.base_url = "http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
    
    def update_lottery_data(self):
        """更新双色球数据"""
        try:
            logging.info("开始更新双色球数据")
            
            # 获取网页内容
            response = requests.get(self.base_url, headers=self.headers, timeout=10)
            response.raise_for_status()
            response.encoding = 'utf-8'
            
            # 解析HTML
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # 查找开奖数据表格
            table = soup.find('table', class_='table-common')
            if not table:
                raise Exception("未找到开奖数据表格")
            
            rows = table.find_all('tr')[1:]  # 跳过表头
            new_count = 0
            total_count = 0
            
            for row in rows:
                try:
                    cells = row.find_all('td')
                    if len(cells) < 8:
                        continue
                    
                    # 解析开奖日期
                    date_text = cells[0].get_text(strip=True)
                    draw_date = datetime.strptime(date_text, '%Y-%m-%d').date()
                    
                    # 解析期数
                    draw_number = cells[1].get_text(strip=True)
                    
                    LotteryResult = get_lottery_model()
                    # 检查是否已存在
                    existing = LotteryResult.query.filter_by(draw_number=draw_number).first()
                    if existing:
                        continue
                    
                    # 解析红球和蓝球
                    numbers_text = cells[2].get_text(strip=True)
                    numbers = re.findall(r'\d+', numbers_text)
                    
                    if len(numbers) != 7:
                        continue
                    
                    red_balls = [int(num) for num in numbers[:6]]
                    blue_ball = int(numbers[6])
                    
                    # 验证号码范围
                    if not all(1 <= ball <= 33 for ball in red_balls):
                        continue
                    if not 1 <= blue_ball <= 16:
                        continue
                    
                    # 创建新记录
                    lottery_result = LotteryResult(
                        draw_date=draw_date,
                        draw_number=draw_number,
                        red_ball_1=red_balls[0],
                        red_ball_2=red_balls[1],
                        red_ball_3=red_balls[2],
                        red_ball_4=red_balls[3],
                        red_ball_5=red_balls[4],
                        red_ball_6=red_balls[5],
                        blue_ball=blue_ball,
                        prize_info=cells[3].get_text(strip=True) if len(cells) > 3 else ''
                    )
                    
                    db.session.add(lottery_result)
                    new_count += 1
                    
                except Exception as e:
                    logging.warning(f"解析行数据失败: {str(e)}")
                    continue
            
            # 提交事务
            db.session.commit()
            LotteryResult = get_lottery_model()
            total_count = LotteryResult.query.count()
            
            logging.info(f"数据更新完成，新增 {new_count} 条，总计 {total_count} 条")
            
            return {
                'new_count': new_count,
                'total_count': total_count
            }
            
        except Exception as e:
            db.session.rollback()
            logging.error(f"更新双色球数据失败: {str(e)}")
            raise
    
    def get_latest_draw(self):
        """获取最新开奖期数"""
        LotteryResult = get_lottery_model()
        return LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
    
    def get_draw_by_number(self, draw_number):
        """根据期数获取开奖结果"""
        LotteryResult = get_lottery_model()
        return LotteryResult.query.filter_by(draw_number=draw_number).first()
    
    def get_draws_by_date_range(self, start_date, end_date):
        """根据日期范围获取开奖结果"""
        LotteryResult = get_lottery_model()
        return LotteryResult.query.filter(
            LotteryResult.draw_date >= start_date,
            LotteryResult.draw_date <= end_date
        ).order_by(LotteryResult.draw_date.asc()).all() 